package com.baidu.manager.modules.sys.controller;

import com.baidu.manager.common.Constant;
import com.baidu.manager.common.exception.JqlException;
import com.baidu.manager.common.utils.Result;
import com.baidu.manager.common.utils.ShiroUtils;
import com.baidu.manager.modules.sys.entity.SysUser;
import com.baidu.manager.modules.sys.service.SysUserService;
import com.baidu.manager.modules.sys.service.SysUserTokenService;
import com.google.code.kaptcha.Constants;
import com.google.code.kaptcha.Producer;
import org.apache.commons.io.IOUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

import static com.baidu.manager.common.utils.ShiroUtils.getUserEntity;
import static com.baidu.manager.common.utils.ShiroUtils.getUserId;

/**
 * @Author: jql
 * @description: TODO(登录相关)
 * @Date: Created by 14:59 2018/4/20
 */
@RestController
public class SysLoginController {

    @Autowired
    private Producer producer;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysUserTokenService sysUserTOkenService;

    @RequestMapping("admin")
    public ModelAndView index(){
        ModelAndView modelAndView = new ModelAndView("/admin/login.html");
        return modelAndView;
    }

    /**
     * 获取验证码
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    @RequestMapping("/captcha.jpg")
    public void captcha(HttpServletResponse response)throws ServletException, IOException{
        response.setHeader("Cache-Control","no-store,no-cache");
        response.setContentType("image/jpeg");

        //生成文字验证码
        String text = producer.createText();
        //生成图片验证码
        BufferedImage image = producer.createImage(text);
        //保存到shiro session
        ShiroUtils.setSessionAttribute(Constants.KAPTCHA_SESSION_KEY,text);

        ServletOutputStream out = response.getOutputStream();
        ImageIO.write(image,"jap",out);
        IOUtils.closeQuietly(out);
    }

    /**
     * 获取登录错误次数
     * @return
     */
    @GetMapping("/sys/getLoginErrorTimes")
    public Result getLoginErrorTimes(){
        Object errorTimes = ShiroUtils.getSessionAttribute(Constant.LOGIN_ERROR_TIMES);
        return Result.ok().put("errorTimes",errorTimes);
    }

    /**
     * 登录
     * @param username
     * @param password
     * @param captcha
     * @return
     * @throws IOException
     */
    @PostMapping("/sys/login")
    public Result login(String username, String password, String captcha)throws IOException{

        Object _login_errors = ShiroUtils.getSessionAttribute(Constant.LOGIN_ERROR_TIMES);
        if (_login_errors == null){
            _login_errors = 0;
        }
        long errorTimes = Long.valueOf(_login_errors.toString());

        //用户信息
        SysUser user = sysUserService.queryByName(username);

        //账号不存在
        if(user == null){
            ShiroUtils.setSessionAttribute(Constant.LOGIN_ERROR_TIMES,++errorTimes);
            return Result.error("账号不存在").put("errorTimes",errorTimes);
        }

        //密码错误
        if (!user.getPassword().equals(new Sha256Hash(password, user.getSalt()).toHex())){
            ShiroUtils.setSessionAttribute(Constant.LOGIN_ERROR_TIMES,++errorTimes);
            return Result.error("密码不正确").put("errorTimes", errorTimes);
        }

        //验证码
        if(errorTimes>=3){
            String kaptcha = getKaptcha(Constants.KAPTCHA_SESSION_KEY);
            if(!captcha.equalsIgnoreCase(kaptcha)){
                ShiroUtils.setSessionAttribute(Constant.LOGIN_ERROR_TIMES,++errorTimes);
                return Result.error("验证码不正确").put("errorTimes", errorTimes);
            }
        }

        //账号锁定
        if (Constant.UserStatus.DISABLE.getValue() == user.getStatus()){
            ShiroUtils.setSessionAttribute(Constant.LOGIN_ERROR_TIMES,++errorTimes);
            return Result.error("账号已被锁定，请联系管理员").put("errorTimes", errorTimes);
        }

        //生成token,并保存到数据库
        Map<String,Object> result = sysUserTOkenService.createToken(user.getId());
        return  Result.ok().put(result);
    }

    @PostMapping("/sys/logout")
    public Result logout(){
        sysUserTOkenService.logout(getUserId());
        return Result.ok();
    }

    /**
     * 从session中获取记录的验证码
     * @param key
     * @return
     */
    private String getKaptcha(String key){
        Object kaptcha = ShiroUtils.getSessionAttribute(key);
        if(kaptcha == null){
            throw new JqlException("验证码已失效");
        }
        ShiroUtils.getSession().removeAttribute(key);
        return kaptcha.toString();
    }
}
